<script setup>
import { onMounted, ref } from 'vue'
import { Edit, Delete, Open } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { addCategory, getCategoryPage, enableOrDisableEmployee, editCategory, deleCategory } from '@/api/category.js'

const drawer = ref(false) //弹层
const name = ref('') //分类名称
const type = ref() //分类类型
const page = ref(1) //分页
const pageSize = ref(10) //每页
const total = ref(0) //总数
const tableData = ref([]) //数据
const classRef = ref()
const loading = ref(false) //加载
const action = ref('')

const classData = ref({
  title: '',
  categoryId: '',
  name: '',
  sort: ''
})

const rules = {
  name: [
    {
      required: true,
      trigger: 'blur',
      validator: (rule, value, callback) => {
        // const reg = /[\u4e00-\u9fa5]/
        var reg = new RegExp('^[A-Za-z\u4e00-\u9fa5]+$')
        if (!value) {
          callback(new Error(this.classData.title + '不能为空'))
        } else if (value.length < 2) {
          callback(new Error('分类名称输入不符，请输入2-20个字符'))
        } else if (!reg.test(value)) {
          callback(new Error('分类名称包含特殊字符'))
        } else {
          callback()
        }
      }
    }
  ],
  sort: [
    {
      required: true,
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (value || String(value) === '0') {
          const reg = /^\d+$/
          if (!reg.test(value)) {
            callback(new Error('排序只能输入数字类型'))
          } else if (Number(value) > 99) {
            callback(new Error('排序只能输入0-99数字'))
          } else {
            callback()
          }
        } else {
          callback(new Error('排序不能为空'))
        }
      }
    }
  ]
}

const options = [
  {
    value: '1',
    label: '零食分类'
  },
  {
    value: '2',
    label: '套餐分类'
  }
]

//
onMounted(() => {
  init()
})

//初始化数据
const init = async () => {
  loading.value = true
  const params = {
    page: page.value,
    pageSize: pageSize.value,
    name: name.value ? name.value : undefined,
    type: type.value ? type.value : undefined
  }
  console.log(params)
  const res = await getCategoryPage(params)

  if (res.data.code === 1) {
    tableData.value = res.data.data.records
    total.value = res.data.data.total
  }
  loading.value = false
}

//禁用启用
const handleStartOrStop = async row => {
  // console.log(row)
  const p = {
    id: row.id,
    status: !row.status ? 1 : 0
  }
  const res = await enableOrDisableEmployee(p)
  if (res.data.code === 1) {
    ElMessage.success('修改状态成功')
    init()
  }
}

//添加
const addClass = st => {
  // console.log(st)
  drawer.value = true
  if (st == 'class') {
    classData.value = {
      title: '新增零食分类',
      type: '1'
    }
  } else {
    classData.value = {
      title: '新增套餐分类',
      type: '2'
    }
  }
  action.value = 'add'
}

//修改
const handleUpdateType = row => {
  console.log(row)
  classData.value = {
    title: '修改分类',
    id: row.id,
    name: row.name,
    sort: row.sort,
    type: row.type
  }
  action.value = 'edit'
  drawer.value = true
}

// 关闭弹窗
const cancelClick = () => {
  drawer.value = false
}

//提交数据
const submitForm = async st => {
  // console.log(classData.value)
  // console.log(action.value)
  //添加
  if (action.value === 'add') {
    const valid = await classRef.value.validate()
    if (valid) {
      const res = await addCategory(classData.value)
      if (res.data.code === 1) {
        ElMessage.success('添加分类成功！')
        cancelClick()
        init()
      }
    }
  } else {
    //修改
    const valid = await classRef.value.validate()
    if (valid) {
      const res = await editCategory(classData.value)
      if (res.data.code === 1) {
        ElMessage.success('修改分类成功！')
        cancelClick()
        init()
      }
    }
  }
}

//删除分类
const DeleteType = async ids => {
  console.log(ids)
  await ElMessageBox.confirm('你确认删除当前分类吗', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })

  const res = await deleCategory(ids)
  if (res.data.code === 1) {
    ElMessage.success('删除分类成功')
    init()
  }
}

//设置每页多少条
const handleSizeChange = val => {
  pageSize.value = val
  init()
}

//设置当前页
const handleCurrentChange = val => {
  page.value = val
  init()
}
</script>

<template>
  <div class="dashboard-container">
    <div class="container">
      <div class="tableBar" style="display: inline-block; width: 100%">
        <label style="margin-right: 10px">分类名称：</label>
        <el-input v-model="name" placeholder="请填写分类名称" style="width: 15%" clearable @clear="init" @keyup.enter.native="init" />

        <label style="margin-right: 5px; margin-left: 20px">分类类型：</label>
        <el-select v-model="type" placeholder="请选择" clearable style="width: 15%" @clear="init">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>

        <el-button class="normal-btn continue" @click="init()">
          查询
        </el-button>

        <div style="float: right">
          <el-button type="primary" class="continue" @click="addClass('class')">
            + 新增零食分类
          </el-button>
          <el-button type="primary" style="margin-left:20px" @click="addClass('meal')">
            + 新增套餐分类
          </el-button>
        </div>

        <el-table v-loading="loading" :data="tableData" style=" margin-top: 30px; width: 100%">
          <el-table-column prop="name" label="分类名称" width="180" align="center" />
          <el-table-column prop="type" label="分类类型" width="180" align="center">
            <template #default="scope">
              <span v-if="scope.row.type === 1">零食</span>
              <span v-else>套餐分类</span>
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" align="center" />
          <el-table-column label="状态" align="center">
            <template #default="scope">
              <span v-if="scope.row.status === 0">禁用</span>
              <span v-else>启用</span>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="操作时间" align="center" />

          <el-table-column label="操作" width="200" align="center">

            <template #default="{row, $index}">
              <el-button type="text" @click="handleStartOrStop(row)">
                {{row.status === 1 ? '禁用' : '启用'}}
              </el-button>

              <el-button type="primary" :icon="Edit" circle plain @click="handleUpdateType(row)"> </el-button>
              <el-button type="danger" :icon="Delete" circle plain @click="DeleteType(row.id)"> </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div>

          <!-- 分页区域 -->
          <el-pagination v-model:current-page="page" v-model:page-size="pagesize" :page-sizes="[2, 5, 10, 40]" :background="true" layout="jumper,total, sizes, prev, pager, next " :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" style="margin-top: 30px; justify-content: flex-end;" />

        </div>
      </div>

    </div>

    <!-- 弹层 -->
    <el-drawer v-model="drawer" :title="classData.title" :before-close="handleClose">
      <el-form ref="classRef" :model="classData" class="demo-form-inline" :rules="rules" label-width="100px">
        <el-form-item label="分类名称：" prop="name">
          <el-input v-model="classData.name" placeholder="请输入分类名称" maxlength="20" />
        </el-form-item>
        <el-form-item label="排序：" prop="sort">
          <el-input v-model="classData.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="cancelClick">取 消</el-button>
        <el-button type="primary" size="medium" @click="submitForm()">确 定</el-button>
        <!-- <el-button v-if="action != 'edit'"
                   type="primary"
                   size="medium"
                   @click="submitForm('go')">
          保存并继续添加
        </el-button> -->
      </span>

    </el-drawer>

  </div>
</template>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 10px;

    .container {
      background: #fff;
      position: relative;
      z-index: 1;
      padding: 30px 28px;
      border-radius: 4px;
      .tableBar {
        display: flex;
        margin-bottom: 20px;
        justify-content: space-between;
      }

      .tableBox {
        width: 100%;
        border: 1px solid;
        border-bottom: 0;
      }

      .pageList {
        text-align: center;
        margin-top: 30px;
      }

      .normal-btn {
        background: #1a89b9;
        color: white;
        margin-left: 20px;
      }
    }
  }
}
</style>